package com.cskaoyan.market.controller;

import com.cskaoyan.market.db.domain.MarketUser;
import com.cskaoyan.market.service.MarketUserService;
import com.cskaoyan.market.util.JacksonUtil;
import com.cskaoyan.market.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import java.util.List;

/**
 * @Author 付诚
 * @Date 2024/5/19 20:20
 * @Version 1.0
 * 加上了update和detail
 */
@RestController
@RequestMapping("admin/user")
public class AdminUserController {
    @Autowired
    private MarketUserService userService;
    //展示所有的用户信息，分页查询
    //逻辑：根据用户输入的查询条件，查询到符合条件的用户信息列表，但是需要注意的是，需要使用分页来操作，并且还需要设定一个排序规则
    @GetMapping("list")
    public Object list(Integer page,Integer limit,String username,String mobile,String sort,String order){

        //处理具体的业务逻辑
        List<MarketUser> marketUserList = userService.list(page,limit, username, mobile, sort, order);
        //返回响应
        return ResponseUtil.okList(marketUserList);
    }


    @PostMapping("update")
    private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        String requestBody = req.getReader().readLine();
        MarketUser marketUser = JacksonUtil.getObjectMapper().readValue(requestBody, MarketUser.class);

        if (marketUser == null) {
            Object object = ResponseUtil.fail();
            String s = JacksonUtil.getObjectMapper().writeValueAsString(object);
            resp.getWriter().println(s);
        }
        userService.update(marketUser);

        int data = 1;
        Object ok = ResponseUtil.ok(data);
        resp.getWriter().println(JacksonUtil.getObjectMapper().writeValueAsString(ok));
    }

    @GetMapping("detail")
    private Object detail(Integer id) {

        //处理具体的业务逻辑
        MarketUser marketUser = userService.detail(id);

        //返回响应
        return ResponseUtil.ok(marketUser);
    }
}
